//
//  AutomationManagerExt.swift
//  home
//
//  Created by Yun Zeng on 2019/9/28.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import Foundation

extension HomeAutomationManager {
    func findAutomationByEventCharacteristic(characteristic: HMCharacteristic) -> HomeAutomation? {
        guard let aid = characteristic.service?.accessory?.id, let sid = characteristic.service?.id else {
            return nil
        }
        let cid = characteristic.id
        for automation in self.automations {
            for event in automation.events {
                switch event.trigger {
                case let .characteristic(trigger):
                    if trigger.aid == aid && trigger.sid == sid && trigger.cid == cid {
                        return automation
                    }
                default:
                    break
                }
            }
        }
        return nil
    }
    
    func findAutomationsByActionCharacteristic(characteristic: HMCharacteristic) -> [HomeAutomation]? {
        guard let aid = characteristic.service?.accessory?.id, let sid = characteristic.service?.id else {
            return nil
        }
        let cid = characteristic.id
        
        var automations = [HomeAutomation]()
        for automation in self.automations {
            if let actions = automation.actions {
                for action in actions {
                    if action.aid == aid && action.sid == sid && action.cid == cid {
                        automations.append(automation)
                        break
                    }
                }
            }
        }
        return automations
    }
}

extension HomeAutomation {
    func getTargetAction(characteristic: HMCharacteristic) -> HomeAction? {
        guard let aid = characteristic.service?.accessory?.id, let sid = characteristic.service?.id else {
            return nil
        }
        let cid = characteristic.id
        
        if let actions = self.actions {
            for action in actions {
                if aid == action.aid && sid == action.sid && cid == action.cid {
                    return action
                }
            }
        }
        return nil
    }
}
